package com.lz.helper.idcard

import android.content.Context
import android.util.Log
import com.IDWORLD.LAPI

//指纹识别, 适用于老像素,
class UFingerRequest(
    context: Context,
    matcher: ByteArray,
    threshold: Float,
    handler: FingerHandler
) : FingerRequest(context, matcher, threshold, handler) {

    companion object {

        //指纹图像质量阀值
        private const val MIN_IMAGE_QUALITY = 70
    }

    override fun run() {
        Log.d(TAG, "...... UFingerRequest thread start ......")

        val api = LAPI(context)
        val image = ByteArray(LAPI.IMAGE_SIZE)
        val template = ByteArray(LAPI.FPINFO_STD_MAX_SIZE)
        val deviceHandle = api.OpenDeviceEx()
//        Log.i(TAG, "deviceHandle...... = $deviceHandle")
        if (deviceHandle == 0L) {
            handler.sendFingerError(OPEN_FAIL)
            return
        }
        handler.sendFingerOpenSuccess()
        while (!isQuit()) {
            await()
            if (isQuit()) break
            var res = api.GetImage(deviceHandle, image)
//            Log.i(TAG, "GetImage...... = $res")
            if (isQuit()) break
            if (res != LAPI.TRUE) {
                errAndDelay(ERR_IMAGE, 500L)
                continue
            }
            res = api.IsPressFinger(deviceHandle, image)
//            Log.i(TAG, "IsPressFinger...... = $res")
            if (isQuit()) break
            if (res == 0) {
                errAndDelay(ERR_UN_PRESS, 500L)
                continue
            }
            res = api.GetImageQuality(deviceHandle, image)
//            Log.i(TAG, "GetImageQuality...... = $res")

            if (isQuit()) break
            if (res < MIN_IMAGE_QUALITY) {
                errAndDelay(ERR_MATCHING)
                continue
            }

            res = api.CreateTemplate(deviceHandle, image, template)
//            Log.i(TAG, "CreateTemplate...... = $res")

            if (isQuit()) break
            if (res == 0) {
                errAndDelay(ERR_MATCHING)
                continue
            }
            res = api.CompareTemplates(deviceHandle, template, matcher)
//            Log.i(TAG, "CompareTemplates......------------------------------- = $res")

            if (isQuit()) break
            if (res < threshold) {
                errAndDelay(ERR_MATCHING)
                continue
            }
            handler.sendFingerResult(res)
            break
        }
        api.CloseDeviceEx(deviceHandle)
        Log.d(TAG, "......... UFingerRequest quit  .............")
    }

    //延时处理
    private fun errAndDelay(err: Int, timeMs: Long = 1000L) {
        handler.sendFingerError(err)
        delay(timeMs)
    }
}